// pages/push-config/push-config.js
const app = getApp();
var uploadImage = require("../../../utils/uploadFile.js");
const request = require("../../../utils/request.js");
var util = require("../../../utils/util.js");
Page({
  /**
   * 页面的初始数据
   */
  data: {
    imgs: [],
    liveinfo:[],
    live_title: "",
    fileHost: "",
    modeItems: [{
        value: "SD",
        title: "标清"
      },
      {
        value: "HD",
        title: "高清"
      },
      {
        value: "FHD",
        title: "超清"
      }
    ],
    mode: "SD",
    orientationItems: [{
        value: "vertical",
        title: "竖屏推流"
      },
      {
        value: "horizontal",
        title: "横屏推流"
      }
    ],
    orientation: "vertical",
    enableCamera: true,
    focusPush: false,
    focusPlay: false,
    tapTime: "", // 防止两次点击操作间隔太快
    headerHeight: app.globalData.headerHeight,
    statusBarHeight: app.globalData.statusBarHeight
  },

  onPushInputTap: function() {
    this.setData({
      focusPush: true
    });
  },
  onPushInputChange: function(e) {
    this.setData({
      pushUrl: e.detail.value
    });
  },
  onPlayInputTap: function() {
    this.setData({
      focusPlay: true
    });
  },
  onPlayInputChange: function(e) {
    this.setData({
      playUrl: e.detail.value
    });
  },
  modeRadioChange: function(e) {
    this.setData({
      mode: e.detail.value
    });
  },
  orientationRadioChange: function(e) {
    this.setData({
      orientation: e.detail.value
    });
  },
  switchChange: function(e) {
    this.setData({
      enableCamera: !e.detail.value
    });
  },
  onScanQR: function() {
    var self = this;
    wx.scanCode({
      onlyFromCamera: true,
      success: res => {
        console.log(res);
        self.setData({
          pushUrl: res.result,
          playUrl: ""
        });
      }
    });
  },
  getlive_title: function(e) {
    var val;
    var that = this;
    if (e.detail == undefined) {
      val = e;
    } else {
      val = e.detail.value;
    }
    this.setData({
      live_title: val
    });
    var params = {
      uniacid: that.data.liveinfo["live"]["uniacid"],
      live_title: val
    };
    app.request.requestPostApi(
      app.globalData.huodiepath2 + "applet/live.php?op=UpLiveUrl",
      params,
      this,
      that.successFun,
      that.failFun
    );
  },
  failFunlogin: function(res, selfObj) {
    wx.setStorage({
      key: 'username',
      data: "",
    })
    wx.setStorage({
      key: 'password',
      data: "",
    })
    wx.showToast({
      title: "服务器出现错误",
      icon: "none",
      duration: 2000
    });
  },
  successFunlogin: function(res, selfObj) {
    console.log(res);
    if (res.status==undefined){
      wx.showToast({
        title: "账号密码错误",
        icon: "none",
        duration: 2000
      });
   return false;
    }
    if (res.status==0) {
      wx.showToast({
        title: res.msg,
        icon: "none",
        duration: 2000
      });
    } else {
      if (res.remainflow<1) {
        wx.setStorageSync("live", res);
        wx.redirectTo({
          url: '/pages/home-page/main',
        })
        wx.showModal({
          title: "提示",
          content: "流量不足请续充流量",
          showCancel: false
        });
        return false;

      }
    
  }
},
  chooseImg: function(e) {
    var that = this;


    var imgs = Array();
    imgs = [];
    that.setData({
      imgs: imgs
    });
    var imgs = this.data.imgs;
    if (imgs.length >= 9) {
      this.setData({
        lenMore: 1
      });
      setTimeout(function() {
        that.setData({
          lenMore: 0
        });
      }, 2500);
      return false;
    }
    wx.chooseImage({

      count: 1, // 默认9
      sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ["album", "camera"], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        var imgs = that.data.imgs;
        var nowTime = util.formatTime(new Date());
        // console.log(tempFilePaths + '----');
        for (var i = 0; i < tempFilePaths.length; i++) {
          wx.showLoading({
            title: "上传中" + (i + 1) + "/" + res.tempFilePaths.length,
            mask: true
          });

          uploadImage(
            res.tempFilePaths[i],
            that.data.fileHost,
            function(result) {
              console.log("======上传成功图片地址为：", result);
              wx.hideLoading();
              var params = {
                uniacid: that.data.liveinfo['live']["uniacid"],
                liveimg: result
              };
              app.request.requestPostApi(
                app.globalData.huodiepath2 + "applet/live.php?op=UpLiveUrl",
                params,
                this,
                that.successFun,
                that.failFun
              );


            },
            function(result) {
              console.log("======上传失败======", result);
              wx.hideLoading();
            }
          );
          if (imgs.length >= 9) {
            that.setData({
              imgs: imgs
            });
            return false;
          } else {
            imgs.push(tempFilePaths[i]);
          }
        }
        // console.log(imgs);
        that.setData({
          imgs: imgs
        });
      }
    });
  },
  failFun: function(res, selfObj) {
    wx.showToast({
      title: "服务器出现错误",
      icon: "none",
      duration: 2000
    });
  },
  successFun: function(res, selfObj) {
    console.log(res);
    var paramsa = {
      username: wx.getStorageSync('username'),
      password: wx.getStorageSync('password')
    };
    console.log(paramsa)
    wx.request({
      url: app.globalData.huodiepath2 + "applet/live.php?op=GetPushLiveInfo",
      data: paramsa,
      method: 'post',
      success(res) {
        console.log(res)
        wx.setStorage({
          key: 'live',
          data: res.data,
        })
      }
    })


  },
  successa(res, obj) {
    console.log('aaaaa')
    console.log(res)
    wx.setStorage({
      key: 'live',
      data: res,
    })
  },
  // 删除图片
  deleteImg: function(e) {
    var imgs = this.data.imgs;
    var index = e.currentTarget.dataset.index;
    imgs.splice(index, 1);
    this.setData({
      imgs: imgs
    });
  },
  // 预览图片
  // previewImg: function(e) {
  //   //获取当前图片的下标
  //   var index = e.currentTarget.dataset.index;
  //   //所有图片
  //   var imgs = this.data.imgs;
  //   wx.previewImage({
  //     //当前显示图片
  //     current: imgs[index],
  //     //所有图片
  //     urls: imgs
  //   });
  // },

  onNewUrlClick: function() {
    var self = this;

    wx.request({
      url: "https://lvb.qcloud.com/weapp/utils/get_test_pushurl",
      success: res => {
        var pushUrl = res.data["url_push"];
        var rtmpUrl = res.data["url_play_rtmp"];
        var flvUrl = res.data["url_play_flv"];
        var hlsUrl = res.data["url_play_hls"];
        var accUrl = res.data["url_play_acc"];
        console.log(pushUrl);
        self.setData({
          pushUrl: pushUrl,
          playUrl: flvUrl
        });

        wx.showToast({
          title: "获取地址成功"
        });
      },
      fail: res => {
        console.log(res);
        wx.showToast({
          title: "网络或服务器异常"
        });
      }
    });
  },
  onCopyPushUrl: function() {
    wx.setClipboardData({
      data: this.data.pushUrl
    });
  },
  onCopyPlayUrl: function() {
    wx.setClipboardData({
      data: this.data.playUrl
    });
  },
  startPush: function() {
    var self = this;
    // 防止两次点击操作间隔太快
    var nowTime = new Date();
    if (nowTime - this.data.tapTime < 1000) {
      return;
    }
    wx.getStorage({
      key: 'live',
      success: function(res) {
        console.log(res)
        var no = wx.getStorageSync("username");
        var pwd = wx.getStorageSync("password");
        var params = {
          username: wx.getStorageSync("username"),
          password: wx.getStorageSync("password")
        };
        app.request.requestPostApi(
          app.globalData.huodiepath2 + "applet/live.php?op=GetPushLiveInfo",
          params,
          self,
          self.successFunlogin,
          self.failFunlogin
        );
      

        if (!res.data.live.liveimg) {
          wx.showModal({
            title: "提示",
            content: "请设置直播封面",
            showCancel: false
          });
          return false;

        } else {
          var url =
            "/pages/live-pusher-demo/push?pushUrl=" +
            encodeURIComponent(self.data.pushUrl) +
            "&mode=" +
            self.data.mode +
            "&orientation=" +
            self.data.orientation +
            "&enableCamera=" +
            self.data.enableCamera;
          console.log(url);
          wx.navigateTo({
            url: url
          });
        }
      },
    })
    if (!self.data.pushUrl || self.data.pushUrl.indexOf("rtmp://") != 0) {
      wx.showModal({
        title: "提示",
        content: "推流地址不合法，请点击自动生成按钮先获取腾讯云推流地址",
        showCancel: false
      });
      return;
    }


    self.setData({
      tapTime: nowTime
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    
    var that = this;
    var live = wx.getStorageSync("live");
    that.setData({
      liveinfo: live
    })

    live = live["live"];
    var myDate = new Date();
    var fileHost = "images/" + live["uniacid"] + "/" + myDate.getFullYear() + "/" + (myDate.getMonth() + 1) + "/";
    this.setData({
      fileHost: fileHost
    });

    var imgs = Array();
    var live_title = live.live_title;
    var playerpush = live.playerpush;
    this.getlive_title(live.live_title);
    imgs.push(app.globalData.huodieimgpath + live["liveimg"]);
    that.setData({
      live: live,
      imgs: imgs,
      live_title: live_title,
      pushUrl: playerpush
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    console.log(" onShareAppMessage");
    return {
      // title: 'RTMP推流',
      // path: '/pages/push/push',
      path: "pages/home-login/main",
      imageUrl:"https://res.lexiangpingou.cn/images/applet/hdassistant_bg.png"
    };
  },
  onBack: function() {
    wx.navigateBack({
      delta: 1
    });
  }
});